package br.ufrn.sigaa.testenotification;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import br.ufrn.arq.mobile.communication.exception.AuthorizationException;
import br.ufrn.arq.mobile.communication.exception.GenericRuntimeMobileException;
import br.ufrn.arq.mobile.communication.exception.RESTChannelFactoryConfigurationException;
import br.ufrn.arq.mobile.communication.rest.DefaultRESTChannel;
import br.ufrn.arq.mobile.communication.rest.HTTPChannel;
import br.ufrn.arq.mobile.communication.rest.RESTChannel;
import br.ufrn.arq.mobile.communication.rest.RESTChannelFactory;
import br.ufrn.arq.mobile.communication.rest.http.HTTPChannelJavaNet;
import br.ufrn.arq.mobile.exception.GenericMobileException;
import br.ufrn.sigaa.mobile.dto.UsuarioDTO;
import br.ufrn.sigaa.mobile.dto.tipos.TipoAutenticacao;
import br.ufrn.sigaa.testenotification.exception.AutenticacaoInvalidaException;

public class LoginActivity extends AccountAuthenticatorActivity implements OnClickListener{

	private RESTChannel sigaaChannel;

	private UsuarioDTO usuarioLogado;
	
	private boolean addConta = false;
	
	public LoginActivity(){
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		addConta = getIntent().getBooleanExtra("addConta", false);
		
		RESTChannel.Builder builder = new SigaaRESTChannelBuilder(getApplicationVersion());
		RESTChannelFactory.initialize(builder);
		
		findViewById(R.id.acessar).setOnClickListener(this);
		
		try {
			sigaaChannel = RESTChannelFactory.getRESTChannel();
			
		} catch (RESTChannelFactoryConfigurationException e) {
			Log.e("SigaaBusinessDelegate", "Error getting RESTChannel", e);
			throw new GenericRuntimeMobileException(e);
		} catch (GenericMobileException e) {
			e.printStackTrace();
		}
		
	}


	public boolean autenticar(String login, String senha, TipoAutenticacao opcaoLogin) throws GenericMobileException, AutenticacaoInvalidaException {

		UsuarioDTO usuarioDTO = null;
		
		try {
			usuarioDTO = sigaaChannel.authenticate(UsuarioDTO.class, login, senha);
	
			if (usuarioDTO != null) {
				setUsuarioLogado(usuarioDTO);
				return true;
			} else {
				return false;
			}
	
		} catch (AuthorizationException e) {
			throw new AutenticacaoInvalidaException(opcaoLogin);
		}
		
	}


	public UsuarioDTO getUsuarioLogado() {
		return usuarioLogado;
	}


	public void setUsuarioLogado(UsuarioDTO usuarioLogado) {
		this.usuarioLogado = usuarioLogado;
	}
	
	@Override
	public void onBackPressed() {
		Intent i = new Intent(this, NotificadorService.class);
		stopService(i);
		super.onBackPressed();
	}

	public int getApplicationVersion(){
		
		int applicationVersion;
		
		try {
			applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
		} catch (Exception e) {
			applicationVersion = 0;
		}
		
		return applicationVersion;
		
	}
	
	class SigaaRESTChannelBuilder  implements RESTChannel.Builder {
		
		private String serverURL;
		private int timeoutValue;
		private int applicationVersion;
		private HTTPChannel httpChannel;
		
		
		public SigaaRESTChannelBuilder(int applicationVersion) {
			
			String baseURL = "";
			String restURL = "";
			int timeoutValue = 0;

			baseURL = getString(R.string.base_url);
			restURL = getString(R.string.server_url);

			try {
				timeoutValue = Integer.valueOf(getString(R.string.TimeoutValue));
			} catch (Exception e) {
				timeoutValue = 0;
			}

			String serverURL = baseURL + restURL;
			

			this.serverURL = serverURL;
			this.timeoutValue = timeoutValue;
			this.applicationVersion = applicationVersion;
			this.httpChannel = HTTPChannelJavaNet.getInstance();

		}


		@Override
		public RESTChannel buildRESTChannel() {
			return DefaultRESTChannel.getInstance(serverURL, timeoutValue, applicationVersion, httpChannel);
		}

	}

	@Override
	public void onClick(View v) {
		
		if (v.getId() == R.id.acessar){
			String login = ((TextView) findViewById(R.id.login)).getText().toString();
			String senha = ((TextView) findViewById(R.id.senha)).getText().toString();
			
			try {
				
				if (autenticar(login, senha, TipoAutenticacao.TOKEN)){
					
					String accountType = this.getIntent().getStringExtra("br.ufrn.sigaa.testenotification");
			        if (accountType == null) {
			        	accountType = "br.ufrn.sigaa.testenotification";
			        }

			        AccountManager accMgr = AccountManager.get(this);

		            // This is the magic that addes the account to the Android Account Manager
		            final Account account = new Account(login, accountType);
		            accMgr.setAuthToken(account, "token", getUsuarioLogado().getTokenAutenticacao());
		            
		            if (accMgr.addAccountExplicitly(account, senha, null)){

			            // Now we tell our caller, could be the Android Account Manager or even our own application
			            // that the process was successful
		            	if (!addConta){
				            final Intent intent = new Intent();
				            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, login);
				            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
				            intent.putExtra(AccountManager.KEY_AUTHTOKEN, accountType);
				            this.setAccountAuthenticatorResult(intent.getExtras());
				            this.setResult(RESULT_OK, intent);
				            this.finish();
		            	} else {
		            		Intent i = new Intent(this, MainActivity.class);
		            		startActivity(i);
		            		this.finish();
		            	}
		            }
				}
				
			} catch (GenericMobileException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (AutenticacaoInvalidaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}
